package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RequestMapping("/menu")
@RestController
public class MenuController {

    @Reference
    MenuService menuService;

    @RequestMapping("/findAll")
    @PreAuthorize("hasAuthority('MENU_QUERY')")
    public Result loadMenu(){
        List<Menu> menuList  = menuService.findAll();

        return Result.success("",menuList);
    }



    @RequestMapping("/add")
    @PreAuthorize("hasAuthority('MENU_ADD')")
    public  Result add(@RequestBody Menu menu){

        try {
            menuService.add(menu);
            return Result.success("添加成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加失败!");
        }

    }

    @RequestMapping("/delete")
    @PreAuthorize("hasAuthority('MENU_DELETE')")
    public Result delete(Integer id){
        try {
            menuService.deleteById(id);
            return Result.success("删除成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败!");
        }

    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        Menu menu = menuService.findById(id);
        return Result.success("",menu);
    }

    @RequestMapping("/edit")
    @PreAuthorize("hasAuthority('MENU_EDIT')")
    public Result edit(@RequestBody Menu menu){
        try {
            menuService.edit(menu);
            return Result.success("修改成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改失败!");
        }

    }
}
